// pages/home/publishDetail/publishDetail.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
//const MessageDB=db.collection('messageData')
const pageSize = 20
var util = require("../../../utils/util.js")
var _item = null   //跳转到详情页传入的item信息
var detailContentID = ""  //该公告ID,通过该ID找该公告的评论
var detailUserLabel = 0  //该公告的用户学院ID，通过该ID找该用户的学院

var totalPage = 0
Page({
  page: 1,
  postflg: true,

  /**
   * 页面的初始数据
   */
  data: {
    detailUserInfo: {},      //公告用户信息
    detailContent: {},       //公告内容
    // detailContentID: "",     //该公告ID,通过该ID找该公告的评论
    // detailUserLabel: 0,      //该公告的用户学院ID，通过该ID找该用户的学院
    detailUserCollege: "",   //该公告用户的学院
    comments: [],            //公告对应的评论
    noComments: "",          //无评论
    content:'',              //留言内容
    focus:false,             //留言框是否聚焦
    // _item:null,              //跳转到详情页传入的item信息
    // totalPage: 0,            //总页数
    messageHidden:true,      //留言框是否隐藏
    refresh_trig:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //全局变量  直接获取  当然要首先在我的登陆才会有数据
    //发布留言肯定需要用户id
    // console.log("用户数据", app.globalData)
    console.log("首次进入",options)
    let that = this
    let item = JSON.parse(options.item)
    // console.log(item)
    // that.setData({
    //   _item: options.item
    // })
    _item = options.item

    if (item) {
      that.setData({
        detailUserInfo: item.userinfo[0], //发公告的用户信息
        detailContent: item.publishContent, //该公告的内容
        // detailContentID: item.publishID, //该公告的ID
        // detailUserLabel: item.userinfo[0].userLabel //发公告用户所属的学院
      })
      detailContentID = item.publishID
      detailUserLabel = item.userinfo[0].userLabel 
      // console.log("detailUserInfo",that.data.detailUserInfo)
      // console.log("detailContent", that.data.detailContent)
      // console.log("detailContentID", that.data.detailContentID)
      // console.log("detailUserLabel", that.data.detailUserLabel)

      that.getAcademy()   //获取发公告用户所属的学院
      that.getComments()  //获取公告对应的留言
    }

  },

  //点击发表留言按钮
  clickMessage:function(){
    console.log("点击留言")
    if (app.globalData.userOpenid == null) {//未登录
      wx.showToast({
        title: '留言前请先登录~',
        icon: "none",
        duration: 2000,
        success: function () {
          setTimeout(function () {
            wx.switchTab({
              url: '../../mine/mine',
            })
          }, 1000);
        }
      })
    } else {
    let that = this
    that.setData({
      messageHidden:false,
      focus:true
    })
  }
  },
 
  //scrollview触底函数
  handlescrolltolower: function () {
    var that = this
    if (that.postflg) {
      that.postflg = false;//请求完成前不再更改页码请求接口
      if (that.page >=totalPage) {
        // wx.showToast({
        //   title: '亲,没有更多留言了',
        //   icon: 'none',
        //   duration: 2000
        // })
      } else {
        that.page++;//页数加一
        that.getComments()
      }
    }
  },

  //获取发布公告人所属的学院
  getAcademy: function () {
    let that = this
    //获取用户所属的学院
    db.collection("collegeData").get({
      success: function (res) {
        // console.log(res)
        if (res.data.length) {
          let allAcademy = res.data[0].allAcademy
          // console.log("allAcademy", allAcademy)
          that.setData({
            detailUserCollege: allAcademy[detailUserLabel].academy
          })
          // console.log("公告对应的用户所属的学院为：", that.data.detailUserCollege)
        }
      },
      fail: function (res) {
        console.error(res)
      }
    })
  },

  //获取留言
  getComments: function () {
    console.log("获取留言")
    var that = this
    // console.log("detailContentID", that.data.detailContentID)
    // console.log("that.data.detailContentID", that.data.detailContentID)
    //获取留言
    wx.cloud.callFunction({
      name: "getDetailComments",
      data: {
        id:detailContentID,
        _page: that.page,
        _pageSize: pageSize
      }
    }).then((res) => {
      // console.log("调用getDetailComments返回的res:",res)
      let index = that.page - 1
      if (res.result.comments.list.length > 0) {
        // let _totalPage = res.result.totalPage
        // console.log("总页数totalPage:", _totalPage)
        totalPage = res.result.totalPage
        that.setData({
          // totalPage: _totalPage,
          ['comments[' + index + ']']: res.result.comments.list
        })
        console.log("comments", that.data.comments)
      } else { //暂时没有评论
        that.setData({
          noComments: "暂时没有留言",
          comments:[]
        })
      }
    })
  },

  //获取留言内容
  getContent: function (e) {
    // console.log("e", e)
    var that = this
    let _content = e.detail.value
    that.setData({
      content: _content
    })
    // console.log("content", that.data.content)
  },

  //将留言内容写入数据库
  sendContent: function () {
    var that = this
    // console.log("this.data.content", that.data.content)
    // console.log("app.globalData.userOpenid", app.globalData.userOpenid)
    // console.log("item",that.data._item)
    // if (app.globalData.userOpenid == null) {//未登录
    //   wx.showToast({
    //     title: '请先登录',
    //     icon: "none",
    //     duration: 2000,
    //     success: function () {
    //       setTimeout(function () {
    //         wx.switchTab({
    //           url: '../../mine/mine',
    //         })
    //       }, 1000);
    //     }
    //   })
    // } else {   //已登录
      if (that.data.content == "") {//输入内容为空
        wx.showToast({
          title: '您还没有输入内容',
          icon: "none",
          duration: 2000,
        })
        that.setData({
          focus: true,
        })
      } else {                      //输入内容不为空
        wx.cloud.callFunction({
          name: 'checkTxt',
          data: {
            txt:that.data.content
          },
          success(res) {
            if (res.result.errCode == 87014) {
              console.log(res.result.errCode)
              wx.showToast({
                icon: 'none',
                title: '含有违法违规内容',
              })
            }else{
            var date = new Date()
            var _date = util.formatTime(date)//时间
            var _messageID = app.globalData.userOpenid //留言人的openId
            var _publishID = detailContentID//公告id (发布者openid+时间戳)
            // console.log("_date ", _date)
            // console.log("_messageID", _messageID)
            // console.log("_publishID", _publishID)
            db.collection('messageData').add({
              data: {
                messageContent: that.data.content,
                messageDate: _date,
                messageID: _messageID,
                publishID: _publishID
              }
            })
              .then(res => {
                console.log("添留言返回的res：",res)
                //清空输入框
                that.setData({
                  content: ""
                })
                wx.showToast({
                  title: '留言成功',
                  success: function () {
                    // setTimeout(function () {
                      //使用页面跳转实现重新渲染留言
                      var tem_item =[]
                      tem_item['item'] =  _item
                      that.onLoad(tem_item)
                      // wx.redirectTo({
                      //   url: 'publishDetail?item=' + that.data._item
                      // })
                    // }, 2000);
                  }
                })
              })
              .catch(console.error)
          }
    }
  })
  }
    // }
  },

  // //设置留言列表高度
  // setHeight: function () {
  //   var that = this
  //   wx.getSystemInfo({
  //     success: function (res) {
  //       // console.log("getSystemInfo:", res)
  //       that.setData({
  //         windowHeight: res.windowHeight,
  //       })
  //     },
  //   })
  //   let query = wx.createSelectorQuery().in(that);
  //   // 然后逐个取出navbar和header的节点信息
  //   // 选择器的语法与jQuery语法相同
  //   query.select('#detail').boundingClientRect();
  //   query.select('#bottom').boundingClientRect();
  //   // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回
  //   query.exec((res) => {
  //     // console.log("res", res)
  //     // 分别取出高度
  //     let detailHeight = parseInt(res[0].height);
  //     let bottomHeight = parseInt(res[1].height);
  //     // 然后就是做个减法
  //     let _scrollViewHeight = that.data.windowHeight - detailHeight - bottomHeight;
  //     // 算出来之后存到data对象里面
  //     // console.log("that.data.windowHeight", that.data.windowHeight)
  //     // console.log("itemHeight", detailHeight)
  //     // console.log("bottomHeight", bottomHeight)
  //     // console.log("scrollViewHeight", _scrollViewHeight)
  //     that.setData({
  //       scrollViewHeight: _scrollViewHeight
  //     });
  //   });
  // },

  previewImage: function (e) {
    app.previewImage(e)
  },
  deleteMessage:function(e){
    console.log(this.data.detailUserInfo._openid)
    let that = this
    let publisherID = that.data.detailUserInfo._openid
    let txt = e.currentTarget.dataset.txt
    let id =e.currentTarget.dataset.id
    if(app.globalData.userOpenid == publisherID){
      console.log(e)
      wx.showActionSheet({
        itemList: ['复制',"删除"],
        success (res) {
          console.log(res.tapIndex)
          if(res.tapIndex==0){
            wx.setClipboardData({
              data: txt,
              success (res) {
                wx.getClipboardData({
                  success (res) {
                    wx.showToast({
                      title: '复制成功',
                    });
                  }
                })
              }
            })
          }else if(res.tapIndex==1){
            wx.showModal({
              title: '提示',
              content: '你确定要删除该条留言？',
              success (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  wx.cloud.callFunction({
                    name:'deleteMessagebyLong',
                    data:{
                      id:id
                    },success:res => {
                      // console.log(res)
                      wx.showToast({
                        title: '删除成功',
                      })
                      var tem_item =[]
                      tem_item['item'] =  _item
                      that.onLoad(tem_item)
                      // wx.redirectTo({
                      //   url: 'publishDetail?item=' + _item
                      // })
                    },
                    fail:res=>{
                      wx.showToast({
                        title: '系统错误',
                        icon:"none"
                      })
                    }
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        },
        fail (res) {
          console.log(res.errMsg)
        }
      })
    }else{
      wx.setClipboardData({
        data: txt,
        success (res) {
          wx.getClipboardData({
            success (res) {
              wx.showToast({
                title: '已复制留言',
              });
            }
          })
        }
      })
    } 
  },
  MyonPullDownRefresh:function(res){
    let that = this
    console.log("下拉刷新")
    var tem_item =[]
    tem_item['item'] =  _item
    that.onLoad(tem_item)
    setTimeout(() => {
      that.setData({
        refresh_trig:false
      })
    }, 2000);
  }
})